package cn.tedu.charging.device.dao.repository;

import cn.tedu.charging.common.pojo.po.ChargingGunInfoPO;
import cn.tedu.charging.device.dao.mapper.ChargingGunInfoMapper;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
@Slf4j
public class GunRepository {
    @Autowired
    private ChargingGunInfoMapper chargingGunInfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    public List<ChargingGunInfoPO> getGunsByStationId(Integer stationId) {
        String stationGunsKey = "station:guns:cache:"+stationId;
        ListOperations<String,ChargingGunInfoPO> listOps = redisTemplate.opsForList();
        List<ChargingGunInfoPO> gunPos = listOps.range(stationGunsKey,0,-1);
        if (CollectionUtils.isNotEmpty(gunPos)){
            log.debug("redis缓存中查询到{}把枪",gunPos.size());
            return gunPos;
        }else {
            log.debug("redis缓存中未查询到枪口");
            gunPos=chargingGunInfoMapper.selectGunsByStationId(stationId);
            if (CollectionUtils.isNotEmpty(gunPos)){
                listOps.leftPushAll(stationGunsKey,gunPos);
            }
            return gunPos;
        }
    }

    public Integer countByIdAndStatus(Integer gunId,Integer status) {
        QueryWrapper<ChargingGunInfoPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",gunId);
        queryWrapper.eq("gun_status",status);
        return chargingGunInfoMapper.selectCount(queryWrapper).intValue();
    }
}
